package com.sf.dlb.service;

import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.NewClassInfo;
import com.sf.dlb.jpa.model.UserNewInfo;
import com.sf.dlb.jpa.repository.NewClassRepository;
import com.sf.dlb.jpa.repository.UserNewRepository;
import com.sf.dlb.config.Global;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.NewClassVO;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class NewClassService {
    private static Logger logger = LoggerFactory.getLogger(NewClassService.class);

    @Autowired
    private NewClassRepository newClassRepository;
    @Autowired
    private UserNewRepository userNewRepository;
    @Autowired
    private UserNewService userNewService;
    @Resource
    private Global global;

    /**
     * 查询所有新闻分类
     * @return
     */
    public ResultVO findByAll(String userId){
        logger.info("findByAll start userId={}",userId);
        List<NewClassInfo> newClassInfos= newClassRepository.findByDelFlagOrderBySortAsc("0");
        if(CollectionUtils.isEmpty(newClassInfos)){
            logger.info("findByAll is newClassInfos null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"查询数据为空");
        }
        //查询用户订阅了那些版块
        UserNewInfo userNewInfo=userNewRepository.findByUserIdAndDelFlag(userId,"0");
        if(userNewInfo==null){
            logger.info("findByUserSubClass userNewInfo==null ");
            userNewInfo=userNewService.initUserNewInfo(userId);
        }
        String classIds=userNewInfo.getClassIds();
        List<String> classIdsList=new ArrayList();
        if(StringUtils.isNotBlank(classIds)){
            String[] classIdsArray=classIds.split(",");
            classIdsList=Arrays.asList(classIdsArray);
        }
        ArrayList<NewClassVO> newClassVOs=new ArrayList<>();
        for (NewClassInfo newClassInfo:newClassInfos) {
            //分类剔除热点
            if(newClassInfo.getClassId().equals("1")){
                continue;
            }
            NewClassVO newClassVO=new NewClassVO();
            BeanUtils.copyProperties(newClassInfo,newClassVO);
            newClassVO.setSubFlag("0");//默认是没有订阅；
            String classIcon=newClassVO.getClassIcon();//全部分类，用户已订阅的图标不一样
            classIcon=classIcon.replaceAll("order","all");
            newClassVO.setClassIcon(global.file_public_ip +classIcon);
            //是否订阅
            for (String str:classIdsList) {
                if(newClassInfo.getClassId().equals(str)){
                    newClassVO.setSubFlag("1");
                }
            }
            newClassVOs.add(newClassVO);
        }
        return ResultVOUtil.success(newClassVOs);
    }
    /**
     * 获取默认分类(未登录)
     * @return
     */
    public ResultVO findByUserSubClass(){
        logger.info("findByUserSubClass start ");
        //查询所有模块
        List<NewClassInfo> newClassInfos= newClassRepository.findByDelFlagOrderBySortAsc("0");
        String defaultClass=global.new_sub_default_class;
        String[] defaultClassArray=defaultClass.split(",");
        List<String> classIdsList=new ArrayList();
        classIdsList=Arrays.asList(defaultClassArray);
        //封装VO
        ArrayList<NewClassVO> newClassVOs=new ArrayList<>();
        for (String str:classIdsList) {
            for (NewClassInfo newClassInfo:newClassInfos) {
                if(str.equals(newClassInfo.getClassId())){
                    NewClassVO newClassVO=new NewClassVO();
                    BeanUtils.copyProperties(newClassInfo,newClassVO);
                    newClassVO.setClassIcon(global.file_public_ip +newClassVO.getClassIcon());
                    newClassVO.setClassPath("news_"+newClassInfo.getClassId());
                    newClassVOs.add(newClassVO);
                    break;
                }
            }
        }
        return ResultVOUtil.success(newClassVOs);
    }
    /**
     * 获取用户订阅的分类
     * @return
     */
    public ResultVO findByUserSubClass(String userId){
        logger.info("findByuserSubClass start userId={}",userId);
        //查询所有模块
        List<NewClassInfo> newClassInfos= newClassRepository.findByDelFlagOrderBySortAsc("0");
        //查询用户订阅了那些版块
        UserNewInfo userNewInfo=userNewRepository.findByUserIdAndDelFlag(userId,"0");
        if(userNewInfo==null){
            logger.info("findByUserSubClass userNewInfo==null ");
            userNewInfo=userNewService.initUserNewInfo(userId);
        }
        String classIds=userNewInfo.getClassIds();
        List<String> classIdsList=new ArrayList();
        if(StringUtils.isNotBlank(classIds)){
            String[] classIdsArray=classIds.split(",");
            classIdsList=Arrays.asList(classIdsArray);
        }
        //封装VO
        ArrayList<NewClassVO> newClassVOs=new ArrayList<>();
        for (String str:classIdsList) {
            for (NewClassInfo newClassInfo:newClassInfos) {
                if(str.equals(newClassInfo.getClassId())){
                    NewClassVO newClassVO=new NewClassVO();
                    BeanUtils.copyProperties(newClassInfo,newClassVO);
                    newClassVO.setClassIcon(global.file_public_ip +newClassVO.getClassIcon());
                    newClassVO.setClassPath("news_"+newClassInfo.getClassId());
                    newClassVOs.add(newClassVO);
                    break;
                }
            }
        }
        return ResultVOUtil.success(newClassVOs);
    }
    /**
     * 增加订阅/取消订阅
     *  增加，取消，都以前端传过来的分类，覆盖已有的分类
     * @return
     */
    @Transactional
    public ResultVO addClassSub(String userId,ArrayList<String> subIdArray){
        logger.info("cencelClassSub start userId={},subIdArray={}",userId,subIdArray.toString());
        //查询用户新闻信息
        UserNewInfo userNewInfo=userNewRepository.findByUserIdAndDelFlag(userId,"0");
        //查询分类的正确排序
        List<NewClassInfo> newClassInfos= newClassRepository.findByDelFlagOrderBySortAsc("0");
        ArrayList<String> classIdSortList=new ArrayList<>();
        classIdSortList.add("1");//默认订阅热点
        for (NewClassInfo newClassInfo:newClassInfos) {
            for (String str:subIdArray) {
                if(StringUtils.equals(str,"1")){
                    continue;//如果主动订阅了热点，就不添加了
                }
                if(StringUtils.equals(newClassInfo.getClassId(),str)){
                    classIdSortList.add(str);
                    break;
                }
            }
        }
        //更新用户订阅的分类
        Object[] toArray= classIdSortList.toArray();
        String toArraystr= StringUtils.join(toArray, ",");
        userNewInfo.setClassIds(toArraystr);
        userNewInfo.setUpdateDate(new Date());
        userNewRepository.save(userNewInfo);
        logger.info("addClassSub end userNewInfo={}", GsonUtils.getInstance().toJson(userNewInfo));
        //返回用户已订阅的分类
        return findByUserSubClass(userId);
    }
}
